<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>动态列表操作</title>
		<style>
			body { font-family: Arial, sans-serif; }
			#wrapper { max-width: 600px; margin: 0 auto; }
			ul { list-style-type: none; padding: 0; }
			li { margin: 8px 0; padding: 8px; border: 1px solid #ddd; }
			button { margin-left: 8px; }
		</style>
	</head>
	<body>
		<div id="wrapper">
			<ul id="currentUl">
				<li>list item1 <button type="button" class="add">插入</button><button type="button" class="del">删除</button></li>
				<li>list item2 <button type="button" class="add">插入</button><button type="button" class="del">删除</button></li>
				<li>list item3 <button type="button" class="add">插入</button><button type="button" class="del">删除</button></li>
				<li>list item4 <button type="button" class="add">插入</button><button type="button" class="del">删除</button></li>
				<li>list item5 <button type="button" class="add">插入</button><button type="button" class="del">删除</button></li>
			</ul>
			<button type="button" id="btn1">在末尾添加元素</button>
			<button type="button" id="btn2">删除最后一个元素</button>
		</div>
		<script>
			const currentUl = document.getElementById("currentUl");
			const btn1 = document.getElementById("btn1");
			const btn2 = document.getElementById("btn2");
			
			// 使用事件委托处理所有按钮点击事件
			currentUl.addEventListener('click', function(e) {
				let target = e.target;
				if (target.classList.contains('add')) {
					insertNewLi(target);
				} else if (target.classList.contains('del')) {
					removeLi(target);
				}
			});
			
			btn1.addEventListener('click', appendLi);
			btn2.addEventListener('click', deleteLast);
			
			function insertNewLi(button) {
				const newLi = createNewLi();
				currentUl.insertBefore(newLi, button.parentNode);
			}
			
			function removeLi(button) {
				currentUl.removeChild(button.parentNode);
			}
			
			function appendLi() {
				const newLi = createNewLi();
				currentUl.appendChild(newLi);
			}
			
			function deleteLast() {
				if (currentUl.lastChild) {
					currentUl.removeChild(currentUl.lastChild);
				}
			}
			
			function createNewLi() {
				const newLi = document.createElement('li');
				// 修复：直接设置文本内容和按钮
				newLi.textContent = 'list item new ';
				
				// 创建插入按钮
				const addBtn = document.createElement('button');
				addBtn.type = 'button';
				addBtn.className = 'add';
				addBtn.textContent = '插入';
				
				// 创建删除按钮
				const delBtn = document.createElement('button');
				delBtn.type = 'button';
				delBtn.className = 'del';
				delBtn.textContent = '删除';
				
				// 添加按钮到li
				newLi.appendChild(addBtn);
				newLi.appendChild(delBtn);
				
				return newLi;
			}
		</script>
	</body>
</html>
    